package com.zhiche.lisa.bms.controller.price;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.lisa.syslog.model.publics.PublicLog;
import com.zhiche.lisa.bms.controller.utils.ToolLogUtils;
import com.zhiche.lisa.bms.dao.model.interfacelog.InterfaceLog;
import com.zhiche.lisa.bms.dao.model.price.PricePurchase;
import com.zhiche.lisa.bms.pojo.dto.price.PricePurchaseAndDtlDTO;
import com.zhiche.lisa.bms.pojo.vo.common.CommonVO;
import com.zhiche.lisa.bms.pojo.vo.price.PricePurchaseVO;
import com.zhiche.lisa.bms.service.price.PricePurchaseService;
import com.zhiche.lisa.bms.service.utils.InterfaceLogUtil;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 支付价格 前端控制器
 * </p>
 *
 * @author liuanshun
 * @since 2018-08-29
 */
@RestController
@RequestMapping(value = "/price")
@Api(value = "/price", description = "支付价格管理接口", tags = {"支付价格管理接口"})
public class PricePurchaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PricePurchaseController.class);

    @Autowired
    private PricePurchaseService pricePurchaseService;

    @Autowired
    private InterfaceLogUtil interfaceLogUtil;

    @Autowired
    private ToolLogUtils toolLogUtils;

    /**
     * 根据条件获取价格列表
     *
     * @param inParam
     * @return
     */
    @PostMapping(value = "/queryPricePurchasePage")
    @ApiOperation(value = "获取支出价格列表", notes = "获取支出价格列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchase.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Page<PricePurchase>> queryPricePurchasePage(@RequestBody @ApiParam(name = "价格分页查询对象", value = "传入json格式以及查询条件", required = true) Page<PricePurchase> inParam) {
        LOGGER.info("PriceController.queryPricePurchasePage Param {} ", inParam);
        RestfulResponse<Page<PricePurchase>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            restful.setData(pricePurchaseService.queryPurchasePage(inParam));
        } catch (BaseException e) {
            LOGGER.error("PriceController.queryPricePurchasePage error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.queryPricePurchasePage error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    /**
     * 获取指定支出价格信息
     *
     * @param inParam
     * @return
     */
    @PostMapping(value = "/getPurchaseByIds")
    @ApiOperation(value = "获取指定支出价格信息", notes = "获取指定支出价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchase.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<List<PricePurchase>> getPurchaseByIds(
            @ApiParam(name = "价格数据查询对象", value = "传入json格式的id数组（ids）", required = true)
            @RequestBody CommonVO inParam) {
        LOGGER.info("PriceController.getPurchaseByIds Param {} ", inParam);
        RestfulResponse<List<PricePurchase>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            restful.setData(pricePurchaseService.getPricePurchaseListByIds(Arrays.asList(inParam.getIds())));
        } catch (BaseException e) {
            LOGGER.error("PriceController.getPurchaseByIds error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.getPurchaseByIds error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    /**
     * 导入支出价格信息
     *
     * @param inParam
     * @return
     */
    @PostMapping(value = "/importPurchase")
    @ApiOperation(value = "导入支出价格信息", notes = "导入支出价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchase.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<String> importPurchase(
            @ApiParam(name = "价格新增对象", value = "传入json格式的支出价格信息", required = true)
            @RequestBody PricePurchase inParam) {
        LOGGER.info("PriceController.importPurchase Param {} ", inParam);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        PublicLog publicLog = new PublicLog();
        try {
            publicLog = toolLogUtils.addToolSystemLog("lisa-tms", "/price/importPurchase",
                    inParam.getWaybillDtlId(), inParam, 0, null);
            pricePurchaseService.insertPurchase(inParam);
            toolLogUtils.addSuccessSystemLog(publicLog);
        } catch (BaseException e) {
            LOGGER.error("PriceController.importPurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.importPurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        LOGGER.info("PriceController.importPurchase end");
        return restful;
    }

    /**
     * 导入支出价格信息
     *
     * @param inParam
     * @return
     */
    @PostMapping(value = "/importPurchaseAndDtl")
    @ApiOperation(value = "导入支出价格信息", notes = "导入支出价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchase.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<String> importPurchaseAndDtl(
            @ApiParam(name = "价格新增对象", value = "传入json格式的支出价格信息", required = true)
            @RequestBody PricePurchaseAndDtlDTO inParam) {
        LOGGER.info("PriceController.importPurchaseAndDtl Param {} ", inParam);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        InterfaceLog interfaceLog = new InterfaceLog();
        PublicLog publicLog = new PublicLog();
        try {
            publicLog = toolLogUtils.addToolSystemLog("huiyunche", "/price/importPurchaseAndDtl",
                    inParam.getWaybillDtlId(), inParam, 0, null);
            interfaceLogUtil.setCalleeCommonLog(interfaceLog, inParam, "/price/importPurchaseAndDtl");
            pricePurchaseService.importPurchaseAndDtl(inParam);
            interfaceLog.setResultMessage("处理生成");
            toolLogUtils.addSuccessSystemLog(publicLog);
        } catch (BaseException e) {
            LOGGER.error("PriceController.importPurchaseAndDtl error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            interfaceLogUtil.setErrorLog(interfaceLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.importPurchaseAndDtl error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            interfaceLogUtil.setErrorLog(interfaceLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        // 保存日志
        interfaceLogUtil.saveInterfaceLog(interfaceLog);
        LOGGER.info("PriceController.importPurchaseAndDtl end");
        return restful;
    }

    /**
     * 批量更新支出价格
     *
     * @param inParam
     * @return
     */
    @PostMapping(value = "/updatePurchase")
    @ApiOperation(value = "批量更新支出价格", notes = "批量更新支出价格", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({
            @ApiResponse(code = 0, message = "success", response = PricePurchase.class),
            @ApiResponse(code = -1, message = "系统异常"),
            @ApiResponse(code = -2, message = "支付价格::无法获取指定信息")
    })
    public RestfulResponse<String> updatePurchase(
            @ApiParam(name = "价格修改对象", value = "传入json格式的实体数组（entityParams）", required = true)
            @RequestBody CommonVO<PricePurchase> inParam) {
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            List<String> msg = pricePurchaseService.updatePurchases(inParam.getEntityParams());
            if (!CollectionUtils.isEmpty(msg)) {
                restful = new RestfulResponse(CommonEnum.ERRORLIST.getCode(), CommonEnum.ERRORLIST.getText(), msg);
            }
        } catch (BaseException e) {
            LOGGER.error("PriceController.updatePurchase error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.updatePurchase error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    @PostMapping(value = "/updateOrInsertPurchase")
    @ApiOperation(value = "更新支出价格信息", notes = "更新支出价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({
            @ApiResponse(code = 0, message = "success", response = PricePurchase.class),
            @ApiResponse(code = -1, message = "系统异常")
    })
    public RestfulResponse<String> updateOrInsertPurchase(
            @ApiParam(name = "价格更新对象", value = "传入json格式的实体数组（entityParams）", required = true)
            @RequestBody PricePurchase pricePurchase) {
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        PublicLog publicLog = new PublicLog();
        try {
            publicLog = toolLogUtils.addToolSystemLog("lisa-tms", "/price/updateOrInsertPurchase",
                    pricePurchase.getWaybillDtlId(), pricePurchase, 0, null);
            pricePurchaseService.updateOrInsertPurchaseByShipTask(pricePurchase);
            toolLogUtils.addSuccessSystemLog(publicLog);
        } catch (BaseException e) {
            LOGGER.error("PriceController.updatePurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.updatePurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    @PostMapping(value = "/deletePurchase")
    @ApiOperation(value = "删除支出价格信息", notes = "删除支出价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({
            @ApiResponse(code = 0, message = "success", response = PricePurchase.class),
            @ApiResponse(code = -1, message = "系统异常")
    })
    public RestfulResponse<String> deletePurchase(
            @ApiParam(name = "价格行数据对象", value = "传入json格式的实体数组（entityParams）", required = true)
            @RequestBody PricePurchase pricePurchase) {
        LOGGER.info("PriceController.deletePurchase Param {} ", pricePurchase);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        InterfaceLog interfaceLog = new InterfaceLog();
        PublicLog publicLog = new PublicLog();
        try {
            publicLog = toolLogUtils.addToolSystemLog("lisa-tms", "/price/deletePurchase",
                    pricePurchase.getShipOrderItemId() +"", pricePurchase, 0, null);
            interfaceLogUtil.setCalleeCommonLog(interfaceLog, pricePurchase, "/price/deletePurchase");
            pricePurchaseService.deletePurchaseByShipOrderItemId(pricePurchase);
            toolLogUtils.addSuccessSystemLog(publicLog);
        } catch (BaseException e) {
            interfaceLogUtil.setErrorLog(interfaceLog, e.getMessage());
            LOGGER.error("PriceController.deletePurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            interfaceLogUtil.setErrorLog(interfaceLog, e.getMessage());
            LOGGER.error("PriceController.deletePurchase error: {}", e.getMessage());
            toolLogUtils.addErrorSystmeLog(publicLog, e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        // 保存日志
        interfaceLogUtil.saveInterfaceLog(interfaceLog);
        LOGGER.info("PriceController.deletePurchase end");
        return restful;
    }

    @PostMapping(value = "/purchaseEnable")
    @ApiOperation(value = "批量生效支出价格", notes = "批量生效支出价格", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({
            @ApiResponse(code = 0, message = "success", response = PricePurchase.class),
            @ApiResponse(code = -1, message = "系统异常"),
            @ApiResponse(code = -2, message = "支付价格::无法获取指定信息")
    })
    public RestfulResponse<String> purchaseEnable(
            @ApiParam(name = "批量价格编辑对象", value = "传入json格式的id数组（ids）", required = true)
            @RequestBody CommonVO<PricePurchase> inParam,
            @RequestHeader("Authorization") String authorization) {
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            List<String> msg = Lists.newArrayList();
            for (Long id :
                    inParam.getIds()) {
                try {
                    pricePurchaseService.enablePurchase(id, authorization);
                } catch (BaseException e) {
                    LOGGER.error("PricePurchaseServiceImpl.purchaseEnable error: {}", e.getMessage());
                    msg.add("支付价格:" + "" + ":" + e.getMessage());
                } catch (Exception e) {
                    LOGGER.error("PricePurchaseServiceImpl.purchaseEnable error: {}", e.getMessage());
                    msg.add("支付价格:" + "" + ":" + "启用失败");
                }
            }
            System.out.println(msg);
            if (!CollectionUtils.isEmpty(msg)) {
                restful = new RestfulResponse(CommonEnum.ERRORLIST.getCode(), CommonEnum.ERRORLIST.getText(), msg);
            }
        } catch (BaseException e) {
            LOGGER.error("/PriceController.puchaseEnable error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        } catch (Exception e) {
            LOGGER.error("/PriceController.puchaseEnable error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }


    /**
     * 修改人送价格信息
     *
     * @param priceVo
     * @return
     */
    @PostMapping(value = "/updateSendDriverPurchasePrice")
    @ApiOperation(value = "修改人送价格信息", notes = "修改人送价格信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchaseVO.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<String> updateSendDriverPurchasePrice(
            @ApiParam(name = "修改人送价格信息", value = "修改人送价格信息", required = true)
            @RequestBody PricePurchaseVO priceVo) {
        LOGGER.info("PriceController.updateSendDriverPurchasePrice Param {} ", priceVo);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            pricePurchaseService.updateSendDriverPurchasePrice(priceVo);
        } catch (BaseException e) {
            LOGGER.error("PriceController.updateSendDriverPurchasePrice error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.updateSendDriverPurchasePrice error: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    /**
     * 补充生成人送应付账款和预付
     *
     * @param orderCodeList
     * @return
     */
    @PostMapping(value = "/replenCreateFeePayableForSendDriver")
    @ApiOperation(value = "补充生成人送应付账款和预付", notes = "补充生成人送应付账款和预付", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = PricePurchaseVO.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<String> replenCreateFeePayableForSendDriver(
            @ApiParam(name = "修改人送价格信息", value = "修改人送价格信息", required = true)
            @RequestBody CommonVO<String> orderCodeList) {
        LOGGER.info("PriceController.replenCreateFeePayableForSendDriver Param {} ", orderCodeList);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            pricePurchaseService.replenCreateFeePayableForSendDriver(orderCodeList.getEntityParams());
        } catch (BaseException e) {
            LOGGER.error("PriceController.replenCreateFeePayableForSendDriver error: {}", e);
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.replenCreateFeePayableForSendDriver error: {}", e);
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    /**
     * 重新推送otm价格到otm
     *
     * @param param entityParams - 指令号集合
     *              typeVal - 是否重新计算价格; 0-否, 1-是, null=否
     * @return
     */
    @PostMapping(value = "/repushHycPriceToOtm")
    public RestfulResponse<Object> repushHycPriceToOtm(@RequestBody CommonVO<String> param) {
        RestfulResponse<Object> result = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            pricePurchaseService.repushHycPriceToOtm(param.getEntityParams(), param.getTypeVal());
        } catch (BaseException e) {
            LOGGER.error("PriceController.repushHycPriceToOtm error: {}", e.getMessage());
            result = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("PriceController.repushHycPriceToOtm error: {}", e.getMessage());
            result = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }
}
